function exit(){
	load();
	//关闭左右页面层
	layer.closeAll('page');
	$("#phone").val("");
	$("#msg").html("");
}


function showInput(obj){
	var reg=/^[1-9]\d*$/;
	if(!reg.test(obj.value)){
		obj.value=1;
		layer.msg("输入不规范");
		var pf = $(obj).parent().prev().text();
		$(obj).parent().next().text(parseFloat(pf));
		multipart();
		findByPhone();
	}else{
		var comId = $(obj).parent().parent().children().eq(0).text();
		var data = {"comId":comId}
		var url = "../../wholeSale/queryInventory.action";
		$.post(url,data,function(mes){
			if(obj.value>mes){
				layer.msg("库存不足您现在最多购买：  "+mes);
				obj.value=mes;
				var pf = $(obj).parent().prev().text();
				$(obj).parent().next().text(parseFloat(pf*mes));
				multipart();
				findByPhone();
			}else{
				var pf = $(obj).parent().prev().text();
				$(obj).parent().next().text(parseFloat(pf*obj.value));
				multipart();
				findByPhone();
			}
		},"json")
	}
}
/**
 * 计算总价
 * @returns
 */
function multipart(){
	var sum = 0;
	$.each($(".sum"),function(index,item){
		money = $(this).html();
		sum+=parseFloat(money);
	});
	if(sum==0){
		$("#heji").html("0");
	}else{
		$("#heji").html(sum);
	}
}

function quxiao(){
	$("#tbody").html("");
	$("#comId").val("");
	$("#snacks").val("");
	$("#snacksNum").val("");
	$("#snacksNum2").val("");
	
	$("#memberId").val("");
}
/**
 * 删除行
 * @param id
 * @returns
 */
function remove(id){
	layer.alert('确定删除此商品么？', {
		closeBtn: 1    // 是否显示关闭按钮
		,anim: 1 //动画类型
		,btn: ['确认','取消'] //按钮
	,yes:function(){
		$("#sc"+id+"").parent().parent().remove();
		//取得文本框的值
		var aa = $("#comId").val();
		//把文本框清空
		$("#comId").val("")
		//文本框的值按取消复选框的id来去除
		var bb = aa.replace(id+"@",'');
		//把值重新赋给文本框
		$("#comId").val(bb);
		//计算总价的方法
		multipart();
		layer.msg('删除成功')
		findByPhone();
	}
	,btn2:function(){
		layer.msg('删除失败')
	}});
}
/**
 * 判断退货数量
 * @param obj
 * @returns
 */
function maxInput(obj){
	var count = $(obj).parent().parent().children().eq(1).text();
	var reg=/^[1-9]\d*$/;
	if(!reg.test(obj.value)){
		layer.msg("输入不规范");
		obj.value=1;
	}else if(parseFloat(obj.value) > parseFloat(count)){
		layer.msg("退货数量不能大于总数量", {icon: 2});
		obj.value=count;
	}
}

layui.use(['form', 'layedit', 'laydate','table'], function(){
	var table = layui.table
	,laydate = layui.laydate
	,form = layui.form
	,layer = layui.layer
	,layedit = layui.layedit;
	table.on('tool(insCom)', function(obj){
		var da = obj.data;
		if(obj.event === 'zj'){
			var data = {"comId":da.comId}
			var url = "../../wholeSale/queryInventory.action";
			$.post(url,data,function(mes){
				if(mes==0){
					layer.msg("不好意思此商品库存不足", {icon: 2});
				}else{
					var　result = true;
					$.each($("#comId").val().split("@"),function(index,item){
						if(item==da.comId){
							layer.msg("您已经加入了此商品", {icon: 2});
							result = false;
						}
					});
					if(result){
						$("#comId").val($("#comId").val()+da.comId+"@");
						$("#tbody").append("<tr>" +
								"<td>"+da.comId+"</td>" +
								"<td>"+da.comName+"</td>" +
								"<td>"+da.comUnit+"</td>" +
								"<td>"+da.ciRetail+"</td>" +
								"<td><input type='text' onkeyup='showInput(this)' value='1' maxlength='5' style='border:0;height:30px;width:100px;text-align:center;'></td>" +
								"<td class='sum'>"+da.ciRetail+"</td>" +
								"<td><a id='sc"+da.comId+"' class='layui-btn layui-btn-danger layui-btn-xs' onclick=remove(\'"+da.comId+"\')>删除</a></td>" +
						"</tr>");
						multipart();
						findByPhone();
						layer.msg('加入成功', {icon: 1});
					}
				}
			},"json");  
		}
	});
	//开始时间
	var startDate=laydate.render({
		elem: '#date',//开始时间ID
		type: 'date',//时间类型
		max:0,//设置一个默认最大值(为当前时间)
		done: function(value, date){
			endDate.config.min ={
					year:date.year,
					month:date.month-1, //关键
					date: date.date,
			};
		}
	});
	//结束时间
	var endDate= laydate.render({
		elem: '#time',//选择器结束时间
		type: 'date',//时间类型
		max:0,//设置一个默认最大值(为当前时间)
		done: function(value,date){
			startDate.config.max={
					year:date.year,
					month:date.month-1,//关键
					date: date.date,
			}
		}
	});

	var $ = layui.$, active = {
			reload: function(){
				var date = $('#date');
				var time = $('#time');
				//执行重载
				table.reload('idTest', {
					page: {
						curr: 1 //重新从第 1 页开始
					}
				,where: {
					date2: date.val(),
					time2: time.val(),
				}
				});
			},
			suwhdetail:function(){
				var snacks= $('#snacks');
				var snacksNum= $('#snacksNum');
				var snacksNum2= $('#snacksNum2');
				//执行重载
				table.reload('test2', {
					page: {
						curr: 1 //重新从第 1 页开始
					}
				,where: {
					comName: snacks.val(),
					onePrice: snacksNum.val(),
					twoPrice: snacksNum2.val()
				}
				});
			}
	};

	$('.demoTable .layui-btn').on('click', function(){
		var type = $(this).data('type');
		active[type] ? active[type].call(this) : '';
	});

	$('#insert').on('click', function(){
		quxiao();
		load();
		layer.open({
			type: 1	 //此处以iframe举例
			,title: '数据增加'
				,offset: 'auto'
					,area: ['1000px', '490px']
		,content:$('#addOrUpdate')
		,success: function(layero){
			//重载表单
			table.reload('test2', {
				page: {
					curr: 1 //重新从第 1 页开始
				}
			});

		},end : function() {
			//弹框关闭的回调函数
			$("#addOrUpdate").hide();
			exit();
			$('.layui-form-checked').click();//关闭已选择
			$("#heji").html("0")
		}
		});
	});
 
	$('#selectphone').on('click', function(){
		findByPhone();
		multipart();
	})
	
	
	$('#jiesuan').on('click', function(){
		if($('#tbody').find('tr').text()==""){
			layer.msg("请选中您要购买的零食", {icon: 2});
		}else{
			layer.confirm('您要购买的商品合计为：'+$("#heji").html()+'￥', {
				
				btn: ['确定'] //按钮
				
			}, function(indexs){
				
				var html = ''; 
				$('#tbody').find('tr').each(function () {
					$(this).find('td').each(function () {
						html += $(this).text()+',';  
					}) 
					html += $(this).find('td:eq(4) input').val()+'#'; 
				})
				var index = layer.load(0, {shade: false});
				var url="../../Retail/add.action";
				var data={"str":html,"sum":$("#heji").html(),"memberId":$("#memberId").val()};
				$.post(url,data,function(mes){
					layer.close(indexs);
					layer.close(index);
					if(mes.state==0){
						$("#addOrUpdate").hide();
						exit();
						parent.layer.msg('增加订单成功！', {
							icon: 1
						});
						$(".layui-laypage-btn")[0].click();//当前表格刷新
					}else{
						parent.layer.msg('增加订单失败', {
							icon: 2
						});
					}
				},"json");

			});
		}
	});
	//监听工具条
	table.on('tool(demo)', function(obj){
		var da = obj.data;
		if(obj.event === 'detail'){
			layer.open({
				type: 2	 
				,title: '零售订单详情'
					,area: ['800px', '200px']
			,offset: 'auto'
				,content:['../../page/zh/detail.html?reId='+da.reId+'','on']
			,end : function() {

			}
			});
		}else if(obj.event === 'salse'){
			$("#comment").val("");
			layer.open({
				type: 1	 
				,title: '退货'
					,area: ['750px', '350px']
			,offset: 'auto'
				,content:$("#calseDiv")
				,success: function(layero){
					//重载表单
					table.reload('test3', {
						page: {
							curr: 1 //重新从第 1 页开始
						}
					});
					
					var url="../../comsaDetail/findRetailAll.action";
					var data={"page":1,"limit":100,"allId":da.reId};
					$.post(url,data,function(mes){
						$("#retaTbody").html("");
						$.each(mes.data,function(index,item){
							$("#retaTbody").append("<tr>"
									+"<td>"+item.comName+"</td>"
									+"<td>"+item.sdCount+"</td>"
									+"<td><input class='saleInput' onkeyup='maxInput(this)' id="+item.sdId+" style='width: 200px;height: 28px;border: none;text-align: center;' type='text' value='1'></td>"
									+"<td>"+item.optime+"</td>"
									+"</tr>");
							var form = layui.form
							form.render();
						});
							
					},"json");
				},end : function() {
					$("#calseDiv").hide();
				}
			});
		}else if(obj.event === 'que'){
			var url="../../comsaDetail/findQue.action";
			var data={"allId":da.reId};
			$.post(url,data,function(mes){
				if(mes==1){
					layer.msg("确认退货成功");
					layer.closeAll('page');
					//重载表单
					table.reload('idTest', {
						page: {
							curr: 1 //重新从第 1 页开始
						}
					});
				}else{
					layer.msg("确认退货失败");
				}
			},"json");
		}
	});
	
	
	
});
function findByPhone(){
	var sum = null;
	$.each($(".sum"),function(index,item){
		money = $(this).text();
		sum+=parseFloat(money);
	});
	
	if($("#comId").val()==""){
		layer.msg("请选中您要购买的零食", {icon: 2});
		$("#msg").html("");
	}else{
		if($("#phone").val() == ""){
			$("#memberId").val("");
			$("#msg").html("");
		}else{
			$("#msg").html("");
			var url="../../member/findPhone.action";
			var data={"phone":$("#phone").val()};
			$.post(url,data,function(mes){
				$("#memberId").val(mes.meId);
				var sss = null;
				if(mes.meDiscount == 3){
					$("#msg").html("您好,你是超级会员!,折扣为7折");
					sss = sum*0.7;
					$("#heji").html(sss.toFixed(2));
				}else if(mes.meDiscount == 2){
					$("#msg").html("您好,你是高级会员!,折扣为8折");
					sss = sum*0.8
					$("#heji").html(sss.toFixed(2));
				}else if(mes.meDiscount == 1){
					$("#msg").html("您好,你是普通会员!,折扣为9折");
					sss = sum*0.9
					$("#heji").html(sss.toFixed(2));
				}else{
					$("#memberId").val("");
					$("#msg").html("您还不是会员哦!赶紧加入我们吧!");
				}
				
			},"json");
		}
	}
}

/*
 * 渲染
 */
function load() {
	var form = layui.form
	form.render();
}
	
$(function(){
	$("#tui").click(function(){
		var sum="";
		$.each($(".saleInput"),function(index,item){
			sum+=item.id+","+$(item).val()+"@";
		});
		
		var url="../../comsaDetail/updateAlear.action";
		var data={"sum":sum,"comment":$("#comment").val()}
		$.post(url,data,function(mes){
			layui.use('table',function(){
				var layer = layui.layer
				,table = layui.table
				if(mes==1){
					layer.msg("保存成功");
					layer.closeAll('page');
					//重载表单
					table.reload('idTest', {
						page: {
							curr: 1 //重新从第 1 页开始
						}
					});
				}else{
					layer.msg("保存失败");
				}
			})
		},"json");
	});
});